package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {


    @Autowired
    private MinioConstantProperties minioConstantProperties;

    //文件上传
    @Override
    public String fileUpload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioConstantProperties.getEndpointUrl())
                        .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                        .build();

        //创建一个bucker桶
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }
        //获取文件名
        String fileName =  UUID.randomUUID().toString().replaceAll("-","")+"."+
                FilenameUtils.getExtension(file.getOriginalFilename());
        minioClient.putObject(PutObjectArgs.builder()
                //设置上传目标存储桶的名称
                .bucket(minioConstantProperties.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());
        String url = minioConstantProperties.getEndpointUrl()+ "/"+minioConstantProperties.getBucketName()+"/"+fileName;
        System.out.println(url);
        return url;
    }
}
